package com.gzx.plugin.tjzy.modular.call.scripts.config;

import com.gzx.plugin.tjzy.modular.call.scripts.entity.GzxCallScripts;
import com.gzx.plugin.tjzy.modular.call.scripts.service.GzxCallScriptsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.tenant.TenantContext;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author zjt
 * @description
 * @date 2025/1/22 17:16
 */
@Component
public class CallScriptInitializationConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private GzxCallScriptsService callScriptService;

    // 使用线程安全的映射以防止并发修改问题
    private static final Map<String, List<String>> callScriptMap = new ConcurrentHashMap<>();

    @Autowired
    public CallScriptInitializationConfig(GzxCallScriptsService callScriptService) {
        this.callScriptService = callScriptService;
    }

    /**
     * 当上下文刷新事件触发时（即应用启动完成），加载数据到静态映射中。
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        loadDataFromDatabase();
    }

    /**
     * 定时任务，每隔一段时间重新加载数据。
     */
    @Scheduled(cron = "0 * * * * ?")// 每分钟执行一次
    public void scheduleLoadData() {
        loadDataFromDatabase();
    }

    private void loadDataFromDatabase() {
        try {
            TenantContext.disableTenantFilter();
            List<GzxCallScripts> callScriptList = callScriptService.listAll();
            callScriptMap.putAll(callScriptList.stream().collect(Collectors.groupingBy(GzxCallScripts::getIntent, Collectors.mapping(GzxCallScripts::getSubject, Collectors.toList()))));
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    public boolean isExitsCallScriptByIntent(String intent) {
        return callScriptMap.containsKey(intent);
    }

    public List<String> getCallScriptMap(String intent) {
        return callScriptMap.get(intent);
    }
}